if (cc.sys.platform === cc.sys.WECHAT_GAME) {
  let SAVE_DATA_KEY = require('SaveDataKey');
  let _openId = null;
  
  function getOpenId(callback) {
    //如果已经取到openid, 就直接返回
    if (_openId) {
      callback(null, _openId);
      return;
    }
    const OPEN_ID_KEY = Global.isDebug ? 'OPEN_ID_KEY_DEBUG' : 'OPEN_ID_KEY';
    
    //先从本地取openId,如果本地没有, 才从云开发取
    let _openId = LocalData.getItem(OPEN_ID_KEY, null);
    if (!_openId) {
      //通过给tmp集合添加一条临时记录, 并取出云数据库自动注入的_openid字段来获取用户openid
      const db = wx.cloud.database();
      const tmp = db.collection('tmp');
      tmp.add({
        data: {},
      }).then(res => {
        let id = res._id;
        tmp.doc(id).get().then(res => {
          _openId = res.data._openid;
          LocalData.setItem(OPEN_ID_KEY, _openId);
          // tmp.doc(id).remove().catch(err => {
          //   Global.PlatformUtils.sendLogEvent('删除tmp记录失败', err);
          // });
          callback(null, _openId);
        }).catch(err => {
          console.error(err);
          Global.PlatformUtils.sendLogEvent('取tmp记录失败', err);
        });
      }).catch(err => {
        console.error(err);
        Global.PlatformUtils.sendLogEvent('add tmp记录失败', err);
        callback(err);
      });
    } else {
      //返回本地的openId
      callback(null, _openId);
    }
  }
  

  
  function loadGameData(callback) {
    getOpenId((err, openid) => {
      if (err) {
        callback(err);
        return;
      }
      let gameData = LocalData.getItem(SAVE_DATA_KEY, null);
      console.log("本地gameData", gameData);
      if (gameData) {
        let res = {
          code: 0,
          gameData: gameData,
          userInfo: {
            id: openid
          },
        };
        callback(null, res);
        return;
      }
      
      const db = wx.cloud.database();
      const players = db.collection('players');
      players.doc(openid).get().then(res => {
        console.log(res);
        callback(null, Object.assign({
            code: 0,
            userInfo: {
              id: openid
            }
          },
          res.data));
      }).catch(err => {
        console.log(err);
        //如果未读取到玩家数据, 就插入默认新数据
        let defaultData = {
          _id: openid,
          gameData: GameConfig.defaultPlayerData,
          shareAward: {},
          inviteCount: 0,
          createTime: db.serverDate()
        };
        players.add({
            data: defaultData
          })
          .then(res => {
            delete defaultData._id;
            defaultData.code = 0;
            defaultData.userInfo = {
              id: openid
            };
            callback(null, defaultData);
          })
          .catch(err => {
            Global.PlatformUtils.sendLogEvent('创建默认player记录失败', err);
            callback(err);
          });
      });
    });
  }
  
  
  function saveGameData(gameData, callback) {
    getOpenId((err, openid) => {
      if (err) {
        callback(err);
        return;
      }
      const db = wx.cloud.database();
      const _ = db.command;
      const players = db.collection('players');
      console.log("wxCloudApiCall.saveGameData开始");
      players.doc(openid).update({
        data: {
          gameData: _.set(gameData)
        }
      }).then(res => {
        console.log("wxCloudApiCall.saveGameData成功", res);
        callback(null, {code: 0});
      }).catch(err => {
        console.log("wxCloudApiCall.saveGameData失败", err);
        Global.PlatformUtils.sendLogEvent('更新player记录失败', err);
        callback(err);
      });
    });
  }
  
  function resetShareAward(callback) {
    getOpenId((err, openid) => {
      if (err) {
        callback(err);
        return;
      }
      const db = wx.cloud.database();
      const _ = db.command;
      const players = db.collection('players');
      
      players.doc(openid).update({
        data: {
          shareAward: _.set({})
        }
      }).then(res => {
        console.log(res);
        callback(null, {code: 0, shareAward: {}});
      }).catch(err => {
        console.log(err);
        Global.PlatformUtils.sendLogEvent('resetShareAward player记录失败', err);
        callback(err);
      });
    });
  }
  
  function inviteReport(data, callback) {
    wx.cloud.callFunction({
        // 云函数名称
        name: 'inviteReport',
        // 传给云函数的参数
        data: data,
      })
      .then(res => {
        let result = res.result;
        if (result.code === 0) {
          callback(null, {code: 0});
        } else {
          callback(result.msg);
        }
      })
      .catch(err => {
        Global.PlatformUtils.sendLogEvent('调用inviteReport云函数失败', err);
        callback(err);
      })
  }
  
  module.exports = {
    getOpenId,
    loadGameData,
    saveGameData,
    resetShareAward,
    inviteReport
  }
}

